from time import sleep
import tkinter as tk

from pubsub import pub

class GuiPiece:
    status_color = ['lightgrey', 'orange', 'green', 'red']

    def __init__(self, total_pieces) -> None:
        
        self.total_pieces = total_pieces
        self.col = 100
        self.row = self.total_pieces // self.col

        self.top = tk.Tk()
        self.w = tk.Canvas(self.top, width = 707, height =8 + 5 + (5 + 2) * self.row )
        self.w.pack()

        self.canvas_init()

        pub.subscribe(self.update_piece, 'piece_change')

    def canvas_init(self):
        r = 0
        c = 0
        cnt = self.total_pieces
        while cnt:
            x = 5 + (5 + 2) * c
            y = 5 + (5 + 2) * r
            self.w.create_rectangle(x, y, x + 5, y + 5, fill = "lightgrey")

            cnt -= 1
            c += 1
            if c >= self.col:
                c = 0
                r += 1
    
    def update_piece(self, index, status):
        r, c = self._index_2_row_col(index)
        x = 5 + (5 + 2) * c
        y = 5 + (5 + 2) * r
        self.w.create_rectangle(x, y, x + 5, y + 5, fill = GuiPiece.status_color[status])
    
    def _index_2_row_col(self, index: int):
        row = index // 100
        col = index % 100
        return row, col
    

if __name__ == "__main__":
    from threading import Thread
    from queue import Queue
    import random


    msg = Queue()

    class backendThread(Thread):
        def __init__(self, name):
            super().__init__()
            self.name = name

        def run(self) -> None:
            
            while True:
                a = random.randrange(0, 1024)
                pub.sendMessage('piece_change', index=a, status=2)
                print('new' + str(a))
                # msg.put(a)
                sleep(random.randrange(0,2))
            return super().run()
    
    class guiThread(Thread):
        def __init__(self, name):
            super().__init__()
            self.name = name

        def run(self) -> None:
            def listener(index, status):
                print(index)
                gui_piece.update_piece(index, status)
            # a = msg.get()
            pub.subscribe(listener, 'piece_change')
            
    
    gui_piece = GuiPiece(1145)

    def listener(index, status):
        print(index)
        gui_piece.update_piece(index, status)
    # a = msg.get()
    pub.subscribe(listener, 'piece_change')

    thread_backend = backendThread(name='backend')
    thread_backend.start()

    # thread_gui = guiThread(name='gui')
    # thread_gui.start()


    gui_piece.top.mainloop()